# -*- coding: utf-8 -*-
import datetime
import decimal
from concurrent.futures import ThreadPoolExecutor
import json
from tornado.web import RequestHandler
from common.settings import HTTP_ASYNC_POOL

__author__ = 'Ennis'


class BaseHttpHandler(RequestHandler):

    def __init__(self, application, request, **kwargs):
        super(BaseHttpHandler, self).__init__(application, request, **kwargs)
        self.executor = ThreadPoolExecutor(HTTP_ASYNC_POOL)

    def data_received(self, chunk):
        pass

    def write(self, chunk):
        if chunk is None:
            msg_info = json.dumps({"result": "success"})
        elif isinstance(chunk, str) is True:
            msg_info = json.dumps({"result": "error", "error": chunk})
        else:
            if isinstance(chunk, dict) is True:
                msg_info = self.toJson({'result': 'success', 'data': chunk})
            else:
                msg_info = chunk
        super(BaseHttpHandler, self).write(msg_info)

    def super_write(self, chunk):
        super(BaseHttpHandler, self).write(chunk)

    # # json to sqlalchemy
    @staticmethod
    def set_field(obj_db, data={}):
        for key in obj_db.__class__.__dict__.keys():
            if key in data:
                setattr(obj_db, key, data[key])

    def toJson(self, data, indent=None):
        return json.dumps(data, cls=CustomJsonEncoder, ensure_ascii=False, indent=indent)


class CustomJsonEncoder(json.JSONEncoder):
    """
    Json解析器，解决识别Decimal出错的问题
    """

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        if isinstance(obj, int):
            return int(obj)
        elif isinstance(obj, float):
            return float(obj)
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        # elif isinstance(obj, array):
        #    return obj.tolist()
        else:
            return super(CustomJsonEncoder, self).default(obj)
